package com.awspaas.user.apps.processforsap.util;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.AbstFileProcessor;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.FileProcessorListener;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.bpms.util.UtilFile;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.remoting.util.StringUtils;
import com.awspaas.user.apps.processforsap.model.BatchInquiry;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

public class FiCreateDataExcelImpl extends AbstFileProcessor implements FileProcessorListener {

    private static final String EXTENSION_XLS = ".xls";
    private static final String EXTENSION_XLSX = ".xlsx";

    @Override
    public void uploadBeforeEncrypt(Map<String, Object> param) {
        super.uploadBeforeEncrypt(param);
    }

    @Override
    public void uploadSuccess(Map<String, Object> param) {
        //文件存储
        DCContext context = (DCContext) param.get("DCContext");
        //上传人
        UserContext uc = context.getSession();
        UtilFile tmpFile = new UtilFile(context.getFilePath());

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(context.getFilePath());
//            inputStream = resource.getInputStream();
            //得到Excel工作簿对象
            Workbook wb = null;
            int available = inputStream.available();
            if (available >= 2000000) {//大于2m的文件给与提示
                context.getDCMessage().setMessage("文件过大会读取异常，请传入小于2m大小的文件或者尝试清除没有数据的单元格样式！！！");
                return;
            }
            if (context.getFilePath().endsWith(EXTENSION_XLS)) {
                wb = new HSSFWorkbook(inputStream);
            } else if (context.getFilePath().endsWith(EXTENSION_XLSX)) {
                wb = new XSSFWorkbook(inputStream);
            }

            if (wb == null) {
                context.getDCMessage().setMessage("读取文件错误");
                return;
            }
            createData(context, wb, uc);

            // 创建数据（包含图片）
            context.getDCMessage().setMessage("导入成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            context.getDCMessage().setMessage(ex.getMessage());
        } finally {
            // 删除
            if (tmpFile != null && tmpFile.length() > 0) {
                tmpFile.delete();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception var23) {
                }
            }
        }
    }

    /**
     * 导入数据
     *
     * @param context dc上下文
     * @param wb      上传的excel附件
     * @param uc      用户上下文
     */
    private void createData(DCContext context, Workbook wb, UserContext uc) {
        String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
        RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);
        //默认参数
        String extParam = context.getExtParam();
        if (StringUtils.isBlank(extParam)) {
            context.getDCMessage().setMessage("读取参数失败，导入失败");
            return;
        }
        //扩展参数
        JSONObject params = JSON.parseObject(extParam);
        //流程实例ID
        String processInstId = params.getString("processInstId");
        //子表表名
        String gridTable = params.getString("gridTable");
        String sql = "select * from BO_EU_FI_ZCLBWH where KMDWM like 'Z4%'";
        List<RowMap> listKMDWN = DBSql.getMaps(sql);

        String sql1 = "select * from bo_act_dict_kv_item where DICTKEY = 'TZWH'";
        List<RowMap> listTZWH = DBSql.getMaps(sql1);

        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 同步读取会自动finish
        List<Object> list = EasyExcel.read(context.getFilePath()).head(BatchInquiry.class).headRowNumber(2).sheet(0).doReadSync();
        List<BO> boList = new ArrayList<>();
        for (Object data : list) {
            // 开始创建子表数据  先获取物料相关信息
            BO gridBo = new BO();
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
            for (String key : jsonObject.keySet()) {
                if ("ANLKL".equals(key.toUpperCase())) {
                    List<RowMap> list1 = listKMDWN.stream().filter(rowMap -> rowMap.getString("KMDWM").equals(jsonObject.get(key))).collect(Collectors.toList());
                    if (list1 != null && list1.size() > 0) {
                        RowMap rowMap = list1.get(0);
                        gridBo.set("ANLKL", jsonObject.get(key));
                        gridBo.set("MENGE", rowMap.getString("DWYW"));
                        gridBo.set("AFASL", rowMap.getString("ZJM"));
                    } else {
                        gridBo.set(key.toUpperCase(), jsonObject.get(key));
                    }
                } else if ("ZTZWH".equals(key.toUpperCase())) {
                    List<RowMap> list1 = listTZWH.stream().filter(rowMap -> rowMap.getString("ITEMNO").equals(jsonObject.get(key))).collect(Collectors.toList());
                    if (list1 != null && list1.size() > 0) {
                        RowMap rowMap = list1.get(0);
                        gridBo.set("ZTZWH", jsonObject.get(key));
                        gridBo.set("ZTZWHMS", rowMap.getString("CNNAME"));
                    } else {
                        gridBo.set(key.toUpperCase(), jsonObject.get(key));
                    }
                } else {
                    gridBo.set(key.toUpperCase(), jsonObject.get(key));
                }
            }
            boList.add(gridBo);
        }

        for (BO bo1 : boList) {
            String iskztsy = bo1.getString("ISKZTSY");
            if ("0".equals(iskztsy)) {
                bo1.set("ZZB", "");
            }
        }
        SDK.getBOAPI().create(gridTable, boList, processInstId, uc.getUID());
    }
}